package com.tinyblog.ajax2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class NewsService {
	private Document dom;
	
	public NewsService() {
		try {
			SAXBuilder builder = new SAXBuilder();
			this.dom = builder.build(NewsService.class.getResource("news.xml"));
		}catch(Exception ex) {
			this.handleError(ex);
		}
	}
	/**
	 * 获取全部的新闻列表
	 * @return
	 */
	public News[] getAllMessage() {
		Collection newslist = new ArrayList();
		if(this.dom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.dom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				News news = new News(element);
				newslist.add(news);
			}while(iterator.hasNext());
			return (News[])newslist.toArray(new News[0]);
		}
		else 
			return new News[0];
	}
	/**
	 * 处理系统异常
	 * @param ex
	 */
	private void handleError(Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.toString());
	}
}
